package com.hellogood.yaohuo.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.shared.entity.Group;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class GroupDAO extends DBHelper {
	Logger log = Logger.getLogger(this.getClass());
	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Group> list = new ArrayList<Group>();
		if (rs != null) {
			while (rs.next()) {
				Group g = new Group();
				g.setGroupCode(rs.getString("GroupCode") == null ? "" : rs.getString("GroupCode").trim());
				g.setGroupName(rs.getString("GroupName") == null ? "" : rs.getString("GroupName").trim());
				list.add(g);
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<Group> getAllGroup() {
		String sql = "SELECT * FROM GROUPS";
		List<?> list = super.query(sql);
		return (List<Group>) list;
	}

	public String addNewGroup(Group g) {
		String sql = "INSERT INTO GROUPS(GROUPCODE,GROUPNAME) VALUES('" + g.getGroupCode() + "','" + g.getGroupName() + "')";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return e.getMessage();
		}
		return "";
	}

	public String removeGroup(String groupCode) {
		String sql = "DELETE FROM GROUPS WHERE GROUPCODE = '" + groupCode + "'";
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return e.getMessage();
		}
		return "";
	}

	public Group getGroupByCode(String code) {
		String sql = "SELECT * FROM GROUPS WHERE GROUPCODE = '" + code + "'";
		List<?> list = super.query(sql);
		if (list == null || list.isEmpty()) {
			return null;
		}
		return (Group) list.get(0);
	}
}
